import React, { Component } from 'react';
import { withRouter, Route } from 'react-router-dom';
import { Icon, Tools, Bubble, ActivityIndicator, PhotoSwipe, Modal } from 'weaver-mobile';
import { RouteLayout } from 'weaver-mobile-page';

import Api from '../../apis/attachment';
import { TitleUtil } from '../../util';
// import ActionButtons from '../widget/ActionButtons';

const { getWeaverFile, getLabel } = Tools;

function getType(name) {
  let type;
  let ext = '';
  name = name.toLowerCase();
  const i = name.lastIndexOf('.');
  if(i > -1){ ext = name.substring(i + 1); }
  switch(ext) {
    case 'doc': case 'docx': case 'wps': case 'txt': case 'md':
      type = 'word'; break;
    case 'rar': case 'zip': case 'gz': case 'z': case '7z':
      type = 'rar';   break;
    case 'xls': case 'xlsx':
      type = 'excel'; break; 
    case 'jpg': case 'png': case 'gif': case 'bmp': case 'jpeg':
      type = 'pic'; break; 
    case 'html': case 'htm': case 'xml': case 'jsp': case 'php': case 'js': case 'css':
      type = 'html'; break;
    case 'pdf':
      type = 'pdf'; break;
    case 'ppt': case 'pptx':
      type = 'combined-shape'; break;
    default:
      type = 'word'; break;
  }
  return type;
}

@withRouter
export default class FilePreview extends Component {

  static defaultProps = {
    prefixCls: "file-preview",
    file: { filename: '' },
  }

  constructor(props) {
    super(props);
    const { id, fileid, isCanPreviewForMobilespan, isCanPreviewForMobile, isImgspan, isImg, downloadUrlspan, previewUrl, filelink, prohibitDownload, prohibitDownloadspan,unPreview,unPreviewspan,previewWmOpen,previewWmOpenspan,ddcode,ddcodespan } = this.props.file;
    this.state = {
      id: id === undefined ? fileid : id,
      isImg: (isImgspan === undefined ? isImg : isImgspan) === 'true',
      isCanPreviewForMobile: (isCanPreviewForMobilespan === undefined ? isCanPreviewForMobile : isCanPreviewForMobilespan) === 'true',
      downloadUrl: downloadUrlspan === undefined ? filelink : downloadUrlspan,
      previewUrl: downloadUrlspan === undefined ? previewUrl : downloadUrlspan,
      filePreviewUrl: '',
      isPreviewable: 0,
      message: '',
      loading: true,
      prohibitDownload:prohibitDownloadspan === undefined ? prohibitDownload : prohibitDownloadspan,
      unPreview:unPreviewspan === undefined ? unPreview : unPreviewspan,
      previewWmOpen:(previewWmOpenspan === undefined ? previewWmOpen : previewWmOpenspan) === 'true',
      ddcode:ddcodespan === undefined ? ddcode : ddcodespan,
    };
  }

  componentDidMount() {
    const isiPhone = Tools.mobileDetect().is('iPhone');
    const isEmobile = Tools.mobileDetect().isEmobile();
    const { history } = this.props;
    const { id, isImg, isCanPreviewForMobile, downloadUrl, previewUrl, prohibitDownload, unPreview, ddcode} = this.state;
    let filePreviewUrl = '';
    window.isUmount = false;
    if("1" == unPreview){
        //禁止预览
        if("1" == prohibitDownload){
          //后台【禁止附件预览】和【禁止移动端下载】同时关闭时，点击附件时需要有提示
          Bubble.warning(getLabel('520701','系统设置原因，该文件只能在PC端下载查看'), 2);
          history.go(-1);
        }else{
          //下载
          this.curentModal = Modal.alert(getLabel('520702','后台邮件系统设置,禁止附件预览'), getLabel('514233','是否下载？'), [
            { text: getLabel('31129', '取消'), onPress: () => { history.go(-1) } },
            { text: getLabel('826', '确定'), onPress: () => {
              if (isiPhone&&!isEmobile) {
                window.open(downloadUrl+"&_ec_ismobile=true&ddcode="+ddcode);
              } else {
                getWeaverFile(downloadUrl+"&_ec_ismobile=true&ddcode="+ddcode, 'iframe','email');
                history.go(-1);
              }
            }},
          ])
        }
    }else{
      if (isImg) {
        TitleUtil.setTitle(getLabel('126994','文件预览'))
        filePreviewUrl = previewUrl;
        this.setState({ loading: false, filePreviewUrl, isPreviewable: 1 });
      } else if (isCanPreviewForMobile) {
        TitleUtil.setTitle(getLabel('126994','文件预览'))
        Api.convertFile({ "fileid":id,"model":"email","convertFile":"pdf" }).then(res => {
          const { convert } = res;
          if("client" == convert){
            const { result, data, message } = res;
            if (!result) {
              filePreviewUrl = Array.isArray(data) && data.length > 0 ? data[0].path : '';
              this.setState({ loading: false, filePreviewUrl, isPreviewable: 1 });
            } else {
              Bubble.error(message, 2);
              history.go(-1);
            }
          }else if("system" == convert){
            const { convertId } = res;
            filePreviewUrl = "/weaver/weaver.file.FileDownload?fileid="+convertId+"&model=email"
            this.setState({ loading: false, filePreviewUrl, isPreviewable: 1 });
          }
          
        });
      } else if (prohibitDownload=="1") {
        //若因文件本身的问题不能预览，移动端也不能下载时，点击附件时需要有提示
        Bubble.warning(getLabel('520703','文件格式等原因，该文件只能在PC端下载查看'), 2);
        history.go(-1);
      } else {
        this.curentModal = Modal.alert(getLabel('514232','当前文件不可预览') , getLabel('514233','是否下载？'), [
          { text: getLabel('31129', '取消'), onPress: () => { history.go(-1) } },
          { text: getLabel('826', '确定'), onPress: () => {
            if (isiPhone&&!isEmobile) {
              window.open(downloadUrl+"&_ec_ismobile=true&ddcode="+ddcode);
            } else {
              getWeaverFile(downloadUrl+"&_ec_ismobile=true&ddcode="+ddcode, 'iframe','email');
              history.go(-1);
            }
          }},
        ])
      }
    }
    
  }

  componentDidUpdate() {
    const { previewWmOpen} = this.state;
    setTimeout(function(){
      if(window.waterMark && !previewWmOpen){
          window.waterMark.destory();
      }
    },1);
  }

  componentWillUnmount() {
    TitleUtil.resetEmElement();
    typeof this.curentModal === 'function' && this.curentModal.close()
  }

  renderIcon = (name) => {
    const { prefixCls } = this.props;
    const icon = getType(name);
    return (<Icon className={`${prefixCls}-filetype icon-${icon}`} type={icon} />);
  }

  render() {
    const { prefixCls, path } = this.props;
    const { loading, filePreviewUrl, isPreviewable, isImg, isCanPreviewForMobile } = this.state;
    if (loading) {
      return (
        <Route
          key="filePreview"
          path={path}
          render={() => (
            <RouteLayout>
              <div key="filePreview" className={`${prefixCls} wm-route-layout`}>
                <div className={`${prefixCls}-loading`}><ActivityIndicator size="large" text="loading..." /></div>
              </div>
            </RouteLayout>
          )}
        />
      );
    } else if (isPreviewable) {
      if (isImg) {
        return (<Route
          key="filePreview"
          path={path}
          render={() => (
            <RouteLayout>
              <div key="filePreview" className={`${prefixCls} wm-route-layout`}>
                <img src={filePreviewUrl} alt="" onClick={() => PhotoSwipe.showImage([{url: filePreviewUrl}], 0)}/>
              </div>
            </RouteLayout>
          )}
        />);
      } else if (isCanPreviewForMobile) {
        // return (<RouteLayout.Frame id="preview-frame" path={path} iframeProps={{ src: filePreviewUrl }} />);
        return (
          <RouteLayout id="preview-frame">
            <div key="Frame" className={`${prefixCls}-frame wm-route-layout`}>
              <div className='wea-doc-openattach'>
                <iframe
                  src={filePreviewUrl}
                />
              </div>
            </div>
          </RouteLayout>
        )
      }
    }
    return null;
  }
}
